package tgc.edu.tms.web.controller;



import java.util.HashSet;

import org.abyss.data.specifications.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.tms.custom.CommonController;
import tgc.edu.tms.entity.Permission;
import tgc.edu.tms.service.PermissionService;
import tgc.edu.tms.web.form.PermissionForm;

@Controller
@RequestMapping(value="/permission")
public class PermissionController extends CommonController<Permission, Integer, PermissionForm>{
	@Autowired
	private PermissionService service;

	@Override
	public Specification<Permission> buildSpec(PermissionForm form) {
		HashSet<Rule> rules=new HashSet<>();
		String name = form.getName();
		if(StringUtils.hasText(name)) {
			rules.add(Rule.property("name").contain(name));
		}
		String code = form.getCode();
		if(StringUtils.hasText(code)) {
			rules.add(Rule.property("code").contain(code));
		}
		String search = form.getSearch();
		if(StringUtils.hasText(search)) {
			HashSet<Rule> rules2=new HashSet<>();
			rules2.add(Rule.property("name").contain(search));
			rules2.add(Rule.property("code").contain(search));
			rules.add(Rule.or(rules2));
		}
		return Rule.and(rules).toSpecification();
	}

	@Override
	public Object save(PermissionForm form) {
		Integer id = form.getId();
		if(id!=null) {
			Permission model = service.findById(id);
			if(!model.getCode().equals(form.getCode())) {
				String oldCode = model.getCode();
				String newCode = form.getCode();
				service.roleChangeCode(oldCode,newCode);
			}
			if(!model.getName().equals(form.getCode())) {
				String oldName = model.getName();
				String newName = form.getName();
				service.roleChangeName(oldName,newName);
			}
		}
		return super.save(form);
	}
	
	
	
	
}
